package icu.sehnen.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author huangqing
 * @version 1.0
 * @date 2021/4/16 11:03
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object usernameInSession = session.getAttribute("USERNAME_IN_SESSION");

        if (usernameInSession != null) {
            return true;
        }

        HashMap map = new HashMap();
        map.put("code", -1);
        map.put("message", "登录过期");
        String result = JSONObject.toJSONString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(result);
        return false;
    }
}
